package com.spring.beanLife.beanInitAndDestroy;

import org.junit.Test;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

public class BeanInitDestroyTest {
	@Test
	public void testCar() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
		printBeans(context);
		context.close();
	}

	private void printBeans(ApplicationContext context) {
		String[] defBeans = context.getBeanDefinitionNames();
		for (String name : defBeans) {
			System.out.println(name);
		}
	}
}

class Toyota implements InitializingBean, DisposableBean {
	public Toyota() {
		System.out.println("Toyota constructor...");
	}

	public void init() {
		System.out.println("Toyota ... init...");
	}

	public void destroy1() {
		System.out.println("Toyota ... destroy...");
	}

	@Override
	public void destroy() throws Exception {
		System.out.println("DisposableBean....Toyota ... destroy...");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("InitializingBean...Toyota...destroy");
	}
}

@Configuration
@ComponentScan("com.spring.beanLife")
class LifeCycleConfig {
	@Bean(initMethod = "init", destroyMethod = "destroy1")
	public Toyota toyota() {
		return new Toyota();
	}
}
